#include "logFile.h"

HttpResponse resp[] = {
    {200, "OK",            "HTTP/1.1 200 OK\r\n\r\n"},
    {400, "Bad request",    "HTTP/1.1 400 Bad request\r\n\r\n"},
    {404, "Not Found",      "HTTP/1.1 404 Not Found\r\n\r\n"},
    {501, "Not Implemented","HTTP/1.1 501 Not Implemented\r\n\r\n"},
    {505, "HTTP Version not supported", "HTTP/1.1 505 HTTP Version not supported\r\n\r\n"}
};

int logFile_init(logFile *logFile, const char *filename,char* mode) {
    logFile->fp= fopen(filename, mode);
    if (logFile->fp == NULL) {
        fprintf(stderr, "Error opening file %s\n", filename);
        return -1;
    }
    logFile->filename = strdup(filename);
    logFile->mode = strdup(mode);
    if (logFile->filename == NULL || logFile->mode == NULL) {
        fprintf(stderr, "Error allocating memory for filename or mode\n");
        fclose(logFile->fp);
        return -1;
    }
    return 0;
}
char *messageGet(HttpResponse res, const char *client_ip, const char *method, const char *path, char* contentLength) {//access_log格式
    char *message = (char *)malloc(512);
    if (message == NULL) {
        fprintf(stderr, "Error allocating memory for message\n");
        return NULL;
    }

    // 获取当前时间（例子"28/Jun/2023:15:30:22 +0800"）
    time_t now = time(NULL);
    struct tm* tm_info = localtime(&now);
    char time_buf[64];
    // char time_buf2[64];
    //格式1：01/Apr/2018:10:37:19 +0800
    strftime(time_buf, sizeof(time_buf), "%d/%b/%Y:%H:%M:%S %z", tm_info);
    //格式2：Thu May 12 08:28:57.652118 2011
    // strftime(time_buf2, sizeof(time_buf2), "%a %b %d %H:%M:%S %Y", tm_info);
    //access_log格式
        snprintf(
            message,
            512,
            "%s - - [%s] \"%s %s HTTP/1.1\" %d %s",//示例格式：192.168.115.5 - - [01/Apr/2018:10:37:19 +0800] "GET / HTTP/1.1" 200 45
            client_ip,
            time_buf,
            method,
            path,
            res.code,
            contentLength
        );
    // else{
    //     int code = res.code;
    //     switch(code){
    //         case 400:
    //             snprintf(
    //                 message,
    //                 512,
    //                 "[%s] [core:error] [pid %d] [client %s] %d:%s",//示例格式：[Thu May 12 08:28:57.652118 2011] [core:error] [pid 8777] [client 192.168.115.5] 400:Bad Request
    //                 time_buf2,
    //                 pid,
    //                 client_ip,
    //                 code,
    //                 "Bad Request"
    //             );
    //             break;
    //         case 404:
    //             snprintf(
    //                 message,
    //                 512,
    //                 "[%s] [core:error] [pid %d] [client %s] %d:%s",
    //                 time_buf2,
    //                 pid,
    //                 client_ip,
    //                 code,
    //                 "Not Found"
    //             );
    //             break;
    //         case 501:
    //             snprintf(
    //                 message,
    //                 512,
    //                 "[%s] [core:error] [pid %d] [client %s] %d:%s",
    //                 time_buf2,
    //                 pid,
    //                 client_ip,
    //                 code,
    //                 "Not Implemented"
    //             );
    //             break;
    //         case 505:
    //             snprintf(
    //                 message,
    //                 512,
    //                 "[%s] [core:error] [pid %d] [client %s] %d:%s",
    //                 time_buf2,
    //                 pid,
    //                 client_ip,
    //                 code,
    //                 "HTTP Version Not Supported"
    //             );
    //             break;
    //         default:
    //             snprintf(
    //                 message,
    //                 512,
    //                 "[%s] [core:error] [pid %d] [client %s] %d:%s",
    //                 time_buf,
    //                 pid,
    //                 client_ip,
    //                 code,
    //                 "Unknown Error"
    //             );
    //             break;
    //     }
    // }
    

    return message;
}
char *ErrorMessageGet(HttpResponse res,const char *client_ip,pid_t pid) {//error_log格式
    char *message = (char *)malloc(512);
    if (message == NULL) {
        fprintf(stderr, "Error allocating memory for message\n");
        return NULL;
    }

    // 获取当前时间（例子"28/Jun/2023:15:30:22 +0800"）
    time_t now = time(NULL);
    struct tm* tm_info = localtime(&now);
    // char time_buf[64];
    char time_buf2[64];
    //格式1：01/Apr/2018:10:37:19 +0800
    // strftime(time_buf, sizeof(time_buf), "%d/%b/%Y:%H:%M:%S %z", tm_info);
    //格式2：Thu May 12 08:28:57.652118 2011
    strftime(time_buf2, sizeof(time_buf2), "%a %b %d %H:%M:%S %Y", tm_info);
    //access_log格式
        // snprintf(
        //     message,
        //     512,
        //     "%s - - [%s] \"%s %s HTTP/1.1\" %d %s",//示例格式：192.168.115.5 - - [01/Apr/2018:10:37:19 +0800] "GET / HTTP/1.1" 200 45
        //     client_ip,
        //     time_buf,
        //     method,
        //     path,
        //     res.code,
        //     contentLength
        // );
    
        int code = res.code;
        switch(code){
            case 400:
                snprintf(
                    message,
                    512,
                    "[%s] [core:error] [pid %d] [client %s] %d:%s",//示例格式：[Thu May 12 08:28:57.652118 2011] [core:error] [pid 8777] [client 192.168.115.5] 400:Bad Request
                    time_buf2,
                    pid,
                    client_ip,
                    code,
                    "Bad Request"
                );
                break;
            case 404:
                snprintf(
                    message,
                    512,
                    "[%s] [core:error] [pid %d] [client %s] %d:%s",
                    time_buf2,
                    pid,
                    client_ip,
                    code,
                    "Not Found"
                );
                break;
            case 501:
                snprintf(
                    message,
                    512,
                    "[%s] [core:error] [pid %d] [client %s] %d:%s",
                    time_buf2,
                    pid,
                    client_ip,
                    code,
                    "Not Implemented"
                );
                break;
            case 505:
                snprintf(
                    message,
                    512,
                    "[%s] [core:error] [pid %d] [client %s] %d:%s",
                    time_buf2,
                    pid,
                    client_ip,
                    code,
                    "HTTP Version Not Supported"
                );
                break;
            default:
                snprintf(
                    message,
                    512,
                    "[%s] [core:error] [pid %d] [client %s] %d:%s",
                    time_buf2,
                    pid,
                    client_ip,
                    code,
                    "Unknown Error"
                );
                break;
        }
    
    

    return message;
}
int logFile_write(logFile *logFile, const char *message) {
    if (logFile->fp == NULL) {
        fprintf(stderr, "File not open\n");
        return -1;
    }
    fprintf(logFile->fp, "%s\n", message);
    fflush(logFile->fp);
    return 0;
}

int logFile_close(logFile *logFile) {
    if (logFile->fp != NULL) {
        fclose(logFile->fp);
        logFile->fp = NULL;
    }
    if (logFile->filename != NULL) {
        free(logFile->filename);
        logFile->filename = NULL;
    }
    if (logFile->mode != NULL) {
        free(logFile->mode);
        logFile->mode = NULL;
    }
    return 0;
}
void access_log(HttpResponse res, struct sockaddr_in *cli_addr, Request* request, char* path, char* content_length) {
    logFile *logfile=malloc(sizeof(logFile));
    logFile_init(logfile,"log.txt","a+");
    char* message=messageGet(res,inet_ntoa(cli_addr->sin_addr),request->http_method,path,content_length);//状态码，主机名，请求方法，请求路径，内容长度
    logFile_write(logfile,message);
    logFile_close(logfile);
    free(logfile);
}
void error_log(HttpResponse res, struct sockaddr_in *cli_addr){
    logFile *logfile=malloc(sizeof(logFile));
    logFile_init(logfile,"log.txt","a+");
    char* message=ErrorMessageGet(res,inet_ntoa(cli_addr->sin_addr),getpid());//状态码，进程号
    printf("%s\n",message);
    logFile_write(logfile,message);
    logFile_close(logfile);
    free(logfile);
}

